//
//  HLHelper.m
//  YueYue
//
//  Created by hulu001 on 2023/5/17.
//

#import "HLHelper.h"
#import <SAMKeychain/SAMKeychain.h>
#import <CL_ShanYanSDK/CL_ShanYanSDK.h>
#import "HLUserInfoRequest.h"

#import "LBXPermission.h"
#import "LBXPermissionMicrophone.h"
#import "LBXPermissionCamera.h"
#import "LBXPermissionLocation.h"

#import "HLLocationManager.h"
#import "HLUserOptionRequest.h"

@implementation HLHelper

+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    static HLHelper *instance;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (NSMutableDictionary *)cache
{
    if (!_cache) {
        _cache = [NSMutableDictionary dictionary];
    }
    return _cache;
}

+ (BOOL)isMale
{
    if ([[HLRunTime shareInstance].mine.sex isEqualToString:@"1"]) {
        return YES;
    }
    return NO;
}

+ (BOOL)isFemale
{
    if ([[HLRunTime shareInstance].mine.sex isEqualToString:@"2"]) {
        return YES;
    }
    return NO;
}


+ (void)userInfo
{
    HLUserInfoRequest *userInfoRequest = [[HLUserInfoRequest alloc] initWithMe];
            
    [userInfoRequest startWithCompletionBlockWithSuccess:^(__kindof HLUserInfoRequest * _Nonnull request) {
        
        if (request.isSuccess){
            HLUserInfoModel *userModel = [request user];
            if (userModel != nil){
                [HLRunTime shareInstance].mine = userModel;
            }
        }
        
    } failure:nil];

}

+ (void)logout
{
    [HLLoginModel deleteWithKeychain];
    [HLRunTime shareInstance].mine = nil;
}

+ (NSString *)getCurrentTimestamp
{
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", time];
    return timeString;
}

+ (NSString *)systemLang
{
    NSArray  *languages        = [NSLocale preferredLanguages];
    NSString *currentLanguage  = [languages objectAtIndex:0];
    NSArray *array = [currentLanguage componentsSeparatedByString:@"-"];
    return array.firstObject;
}

+ (NSString *)systemArea
{
    NSArray  *languages        = [NSLocale preferredLanguages];
    NSString *currentLanguage  = [languages objectAtIndex:0];
    NSArray *array = [currentLanguage componentsSeparatedByString:@"-"];
    
    
    NSString *systemArea = array.lastObject;
    
    return systemArea;
}



+ (NSString *)area
{
    NSString *current_system_lang = [NSUserDefaults.standardUserDefaults valueForKey:@"current_system_lang"];
    
    if (current_system_lang) {
        
        if ([current_system_lang hasPrefix:@"zh-Hans"]) {
          //开头匹配
            return @"CN";
        } else if ([current_system_lang hasPrefix:@"zh-Hant"] || [current_system_lang hasPrefix:@"zh-HK"]) {
            return @"HK";
        } else if ([current_system_lang hasPrefix:@"vi"]) {
            return @"VN";
        } else {
            return @"US";
        }
    } else {
        return @"US";
    }
}

+ (void)shanYanLoadWithCallback:(dispatch_block_t)callback
{
    [CLShanYanSDKManager preGetPhonenumber:^(CLCompleteResult * _Nonnull completeResult) {
        HLShanYanModel *data = [HLShanYanModel mj_objectWithKeyValues:completeResult.data];
        if(data){
            HLRunTime.shareInstance.shanYan = data;
        }
        if (callback){
            callback();
        }
    }];
}

+ (NSString *)language
{
    NSString *currentLanguage = @"zh-cn";
    // 无论是从系统获取还是APP内切换语言获取，当前的currentLanguage是包含简体繁体，例如zh-hans、zh-hant，需要再进一步剔除hans，hant。从而满足服务器要求
    
    NSString *lang = @"en";
    lang = [currentLanguage componentsSeparatedByString:@"-"].firstObject;
    
    if (lang.length == 0) {
        return @"en";
    }
    
    return lang;
}

/** IMEI */
+ (NSString *)IMEI
{
    NSString * currentDeviceUUIDStr = [SAMKeychain passwordForService:@" "account:@"uuid"];
    if (currentDeviceUUIDStr == nil || [currentDeviceUUIDStr isEqualToString:@""])
    {
        NSUUID * currentDeviceUUID  = [UIDevice currentDevice].identifierForVendor;
        currentDeviceUUIDStr = currentDeviceUUID.UUIDString;
        currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
        currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];
        [SAMKeychain setPassword: currentDeviceUUIDStr forService:@" "account:@"uuid"];
    }
    return currentDeviceUUIDStr;
}

+ (NSString*)addTokenParamWithBaesURL:(NSString *)baseURL
{
    NSString *urlString = baseURL;
    NSString *channel = @"AppStore";
    NSString *clientId = ClientID;
    NSString *deviceId = [self IMEI];
    NSString *lang = [self language];
    NSString *phoneSys = @"ios";
    NSString *version = NSBundle.mainBundle.infoDictionary[@"CFBundleShortVersionString"];
    NSString *Authorization = HLLoginModel.dataWithKeychain.token;
    NSString *inviteCode = [HLRunTime shareInstance].mine.inviteNo;
    NSString *countryCode = [HLRunTime shareInstance].mine.countryId;
    NSString *url = [NSString stringWithFormat:@"%@?channel=%@&clientId=%@&deviceId=%@&lang=%@&phoneSys=%@&version=%@&Authorization=%@&countryCode=%@",urlString,channel,clientId,deviceId,lang,phoneSys,version,Authorization,countryCode];
    if (inviteCode.length > 0){
        url = [NSString stringWithFormat:@"%@&inviteCode=%@",url, inviteCode];
    }
    
    return url;
}

+ (CGSize)sizeWithImageOriginSize:(CGSize)originSize
                              minSize:(CGSize)imageMinSize
                              maxSize:(CGSize)imageMaxSize
{
    CGSize size;
    NSInteger imageWidth = originSize.width ,imageHeight = originSize.height;
    NSInteger imageMinWidth = imageMinSize.width, imageMinHeight = imageMinSize.height;
    NSInteger imageMaxWidth = imageMaxSize.width,  imageMaxHeight = imageMaxSize.height;
    if (imageWidth > imageHeight) //宽图
    {
        size.height = imageMinHeight;  //高度取最小高度
        size.width = imageWidth * imageMinHeight / imageHeight;
        if (size.width > imageMaxWidth)
        {
            size.width = imageMaxWidth;
        }
    }
    else if(imageWidth < imageHeight)//高图
    {
        size.width = imageMinWidth;
        size.height = imageHeight *imageMinWidth / imageWidth;
        if (size.height > imageMaxHeight)
        {
            size.height = imageMaxHeight;
        }
    }
    else//方图
    {
        if (imageWidth > imageMaxWidth)
        {
            size.width = imageMaxWidth;
            size.height = imageMaxHeight;
        }
        else if(imageWidth > imageMinWidth)
        {
            size.width = imageWidth;
            size.height = imageHeight;
        }
        else
        {
            size.width = imageMinWidth;
            size.height = imageMinHeight;
        }
    }
    return size;
}


+ (NSString *)changeVideoPhasset:(PHAsset*)asset
{
    
    [QMUITips showLoading:@"正在转换视频..." inView:[HLUIHelper keyWindow]];
    
    NSString * vPath = [NSString stringWithFormat:@"%@/video.mp4",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
    
   NSFileManager *fileManager = [NSFileManager defaultManager];
   [fileManager removeItemAtPath:vPath error:nil];
   
   PHVideoRequestOptions *option = [[PHVideoRequestOptions alloc] init];
   option.version = PHVideoRequestOptionsVersionCurrent; // default
   option.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic; // default
   
   // Manager
   PHImageManager *manager = [PHImageManager defaultManager];
   [manager requestExportSessionForVideo:asset options:option exportPreset:AVAssetExportPresetHighestQuality  resultHandler:^(AVAssetExportSession * _Nullable exportSession, NSDictionary * _Nullable info) {
       exportSession.outputURL = [NSURL fileURLWithPath:vPath];
       exportSession.shouldOptimizeForNetworkUse = NO;
       exportSession.outputFileType = AVFileTypeMPEG4; // mp4
       [exportSession exportAsynchronouslyWithCompletionHandler:^{
           dispatch_sync(dispatch_get_main_queue(), ^{
               [QMUITips hideAllTips];
           });
           switch ([exportSession status]) {
               case AVAssetExportSessionStatusFailed:
               {
                   dispatch_sync(dispatch_get_main_queue(), ^{
                       [QMUITips showWithText:@"转换失败"];
                   });
               }    break;
               case AVAssetExportSessionStatusCompleted:
               {
                   dispatch_sync(dispatch_get_main_queue(), ^{
                       NSURL *url = [NSURL fileURLWithPath:vPath];
                       NSNumber *size;
                       [url getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
                       CGFloat sizeM = [size floatValue]/(1024.0*1024.0);
                       if (sizeM>50) {
                           [QMUITips showWithText:@"视频不能大于50M，请重新选择"];
                           return;
                       }
                   });
                   
               }    break;
               default:
                   break;
           }
       }];
   }];
    return vPath;
}

+ (BOOL)IMFilterWithSessionId:(NSString *)sessionId
{
    if ([sessionId isEqualToString:@"230101"]
        || [sessionId isEqualToString:@"230102"]
        || [sessionId isEqualToString:@"230103"]
        || [sessionId isEqualToString:@"1"]
        || [sessionId isEqualToString:@"2"]
        || [sessionId isEqualToString:@"3"]){
        return YES;
    }
    return NO;
}

+ (BOOL)authorizationStatus
{
    // 声音权限检测
    NSInteger status = [LBXPermissionMicrophone authorizationStatus];
    if (status == 0) {
        [LBXPermissionMicrophone authorizeWithCompletion:^(BOOL granted, BOOL firstTime) {
            if (granted == NO) {
                [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"权限提醒" msg:@"使用此功能必须先允许麦克风访问权限。点击“去允许”跳到系统设置->隐私权限，开启麦克风权限" cancel:@"取消" setting:@"去授权"];
            }
        }];
        return NO;
    }
    if (status == 1) {
        [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"权限提醒" msg:@"使用此功能必须先允许麦克风访问权限。点击“去允许”跳到系统设置->隐私权限，开启麦克风权限" cancel:@"取消" setting:@"去授权"];
        return NO;
    }
    // 摄像头权限检测
    if ([LBXPermissionCamera authorizationStatus] == 0) {
        [LBXPermissionCamera authorizeWithCompletion:^(BOOL granted, BOOL firstTime) {
            if (granted == NO) {
                [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"权限提醒" msg:@"使用此功能必须先允许摄像头使用权限。点击“去允许”跳到系统设置->隐私权限，开启摄像头使用权限" cancel:@"取消" setting:@"去授权"];
            }
        }];
        return NO;
    }
    if ([LBXPermissionCamera authorizationStatus] == 1 || [LBXPermissionCamera authorizationStatus] == 2) {
        [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"权限提醒" msg:@"使用此功能必须先允许摄像头使用权限。点击“去允许”跳到系统设置->隐私权限，开启摄像头使用权限" cancel:@"取消" setting:@"去授权"];
        return NO;
    }
    
//    if([LBXPermissionLocation authorizationStatus] == 0){
//        [LBXPermissionLocation authorizeWithCompletion:^(BOOL granted, BOOL firstTime) {
//            if (granted == NO) {
//                [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"权限提醒" msg:@"使用此功能必须先允许GPS使用权限。点击“去允许”跳到系统设置->定位服务，开启GPS使用权限" cancel:@"取消" setting:@"去授权"];
//            }
//        }];
//        return NO;
//    }
    
//    if ([LBXPermissionLocation authorizationStatus] == 1 || [LBXPermissionLocation authorizationStatus] == 2) {
//        [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"权限提醒" msg:@"使用此功能必须先允许GPS使用权限。点击“去允许”跳到系统设置->定位服务，开启GPS使用权限" cancel:@"取消" setting:@"去授权"];
//        return NO;
//    }
//    
    return YES;
}


+ (void)getLocalManager
{
    [LBXPermissionLocation authorizeWithCompletion:^(BOOL granted, BOOL firstTime) {
        if (granted) {
            [[HLLocationManager sharedManager] startGps:^(CLLocation *currentLocation) {
                [HLLocationManager converseGps:currentLocation success:^(CLPlacemark *place) {
                    CLLocationCoordinate2D coordinate = [currentLocation coordinate];
                    NSString *identifier = [NSString stringWithFormat:@"%.3f-%.3f",coordinate.latitude, coordinate.longitude];
                    [QMUIHelper executeBlock:^{
                        [HLLocationManager sharedManager].latitude = coordinate.latitude;
                        [HLLocationManager sharedManager].longtitude = coordinate.longitude;
                        [HLLocationManager sharedManager].city = place.locality;
                        [[HLLocationManager sharedManager] stopGps];
                        
                    } oncePerIdentifier:identifier];
                    
                } fail:^(NSError *error) {
                    [[HLLocationManager sharedManager] stopGps];
                    [QMUITips showError:error.localizedDescription];
                }];
            } fail:^(NSError *error) {
                [[HLLocationManager sharedManager] stopGps];
                [QMUITips showError:error.localizedDescription];
            }];
            
        }
    }];
    
}

+ (CGSize)stringSizeWithFont:(UIFont *)font str:(NSString*)str maxWidth:(CGFloat)maxWidth maxHeight:(CGFloat)maxHeight
{
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    CGSize maxSize = CGSizeMake(maxWidth, maxHeight);
    attr[NSFontAttributeName] = font;
    return [str boundingRectWithSize:maxSize options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attr context:nil].size;
    
}

+ (NSString *)showTime:(NSTimeInterval)msglastTime showDetail:(BOOL)showDetail
{
    //今天的时间

    NSDate * msgDate = [NSDate dateWithTimeIntervalSince1970:msglastTime];
    return [self showDate:msgDate showDetail:showDetail];
}

+ (NSString *)showDateString:(NSString *)dateString
{
    NSDate *date = [NSDate br_dateFromString:dateString dateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [self showDate:date showDetail:YES];
}

+ (NSString *)showDate:(NSDate *)msgDate showDetail:(BOOL)showDetail
{
    NSDate * nowDate = [NSDate date];
    NSString *result = nil;
    NSCalendarUnit components = (NSCalendarUnit)(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitHour | NSCalendarUnitMinute);
    NSDateComponents *nowDateComponents = [[NSCalendar currentCalendar] components:components fromDate:nowDate];
    NSDateComponents *msgDateComponents = [[NSCalendar currentCalendar] components:components fromDate:msgDate];
    
    NSInteger hour = msgDateComponents.hour;
    double OnedayTimeIntervalValue = 24*60*60;  //一天的秒数

    result = [self getPeriodOfTime:hour withMinute:msgDateComponents.minute];
    if (hour > 12)
    {
        hour = hour - 12;
    }
    
    BOOL isSameMonth = (nowDateComponents.year == msgDateComponents.year) && (nowDateComponents.month == msgDateComponents.month);
    
    if(isSameMonth && (nowDateComponents.day == msgDateComponents.day)) //同一天,显示时间
    {
        result = [[NSString alloc] initWithFormat:@"%@ %zd:%02d",result,hour,(int)msgDateComponents.minute];
    }
    else if(isSameMonth && (nowDateComponents.day == (msgDateComponents.day+1)))//昨天
    {
        result = showDetail?  [[NSString alloc] initWithFormat:@"%@ %@ %zd:%02d", @"昨天",result,hour,(int)msgDateComponents.minute] : @"昨天";
    }
    else if(isSameMonth && (nowDateComponents.day == (msgDateComponents.day+2))) //前天
    {
        result = showDetail? [[NSString alloc] initWithFormat:@"%@ %@ %zd:%02d",@"前天",result,hour,(int)msgDateComponents.minute] : @"前天";
    }
    else if([nowDate timeIntervalSinceDate:msgDate] < 7 * OnedayTimeIntervalValue)//一周内
    {
        NSString *weekDay = [self weekdayStr:msgDateComponents.weekday];
        result = showDetail? [weekDay stringByAppendingFormat:@" %@ %zd:%02d",result,hour,(int)msgDateComponents.minute] : weekDay;
    }
    else//显示日期
    {
        NSString *day = [NSString stringWithFormat:@"%zd年%zd月%zd日", msgDateComponents.year, msgDateComponents.month, msgDateComponents.day];
        result = showDetail? [day stringByAppendingFormat:@"%@ %zd:%02d",result,hour,(int)msgDateComponents.minute]:day;
    }
    return result;
}


+ (NSString *)getPeriodOfTime:(NSInteger)time withMinute:(NSInteger)minute
{
    NSInteger totalMin = time *60 + minute;
    NSString *showPeriodOfTime = @"";
    if (totalMin > 0 && totalMin <= 5 * 60)
    {
        showPeriodOfTime = @"凌晨";
    }
    else if (totalMin > 5 * 60 && totalMin < 12 * 60)
    {
        showPeriodOfTime = @"上午";
    }
    else if (totalMin >= 12 * 60 && totalMin <= 18 * 60)
    {
        showPeriodOfTime = @"下午";
    }
    else if ((totalMin > 18 * 60 && totalMin <= (23 * 60 + 59)) || totalMin == 0)
    {
        showPeriodOfTime = @"晚上";
    }
    return showPeriodOfTime;
}

+(NSString*)weekdayStr:(NSInteger)dayOfWeek
{
    static NSDictionary *daysOfWeekDict = nil;
    daysOfWeekDict = @{@(1):@"星期日",
                       @(2):@"星期一",
                       @(3):@"星期二",
                       @(4):@"星期三",
                       @(5):@"星期四",
                       @(6):@"星期五",
                       @(7):@"星期六",};
    return [daysOfWeekDict objectForKey:@(dayOfWeek)];
}

+ (NSString *)showTimeInCall:(int)seconds
{
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",(long)seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(long)(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",(long)seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    
    // 不满1小时 分:秒 两段式
    if (seconds/3600 == 0) {
        return [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    }
    
    return format_time;
}

+ (NSTimeInterval)currentTimeStamp
{
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] * 1000;
    return interval;
}

+ (NSInteger)getTimeIntervalFromStartTime:(NSTimeInterval)startTime toEndTime:(NSTimeInterval)endTime
{
    NSTimeInterval timeInterval = endTime/1000 - startTime;
    return timeInterval;
}


// 恋爱铃相关
+ (void)toggleLoveBell
{
    [[NSUserDefaults standardUserDefaults] setBool:![self loveBell] forKey:kUserLoveBell];
}
+ (BOOL)loveBell
{
    return ![[NSUserDefaults standardUserDefaults] boolForKey:kUserLoveBell];
}

// 今日恋爱铃开关
+ (void)toggleLoveBellToday
{
    if ([self loveBellToday]){
        [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:kUserTodyLoveBell];
    } else{
        NSDate *now = [NSDate date];
        [[NSUserDefaults standardUserDefaults] setValue:now forKey:kUserTodyLoveBell];
    }
    
}
+ (BOOL)loveBellToday
{
     NSDate *currentDate = [[NSUserDefaults standardUserDefaults] objectForKey:kUserTodyLoveBell];
     if ([currentDate isKindOfClass:[NSDate class]]) {
         return ([currentDate br_day] == [[NSDate date] br_day]);
     }
     
     return false;
}

@end
